//
//  MessageController.swift
//  消息界面
//  会话界面
//
//  Created by smile on 2019/4/22.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//发布订阅框架
import SwiftEventBus

class MessageController: BaseTitleController {

    /// 列表控制
    @IBOutlet weak var tableView: UITableView!
    
    var dataArray:[JMSGConversation] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func initViews() {
        super.initViews()
        setTitle("我的消息")
    }
    
    override func initDatas() {
        super.initDatas()
    }
    
    override func initListeners() {
        super.initListeners()
    }
    
    func fetchData() {
        dataArray.removeAll()
        
        //获取所有的会话
        JMSGConversation.allConversations { (datas, error) in
            if error == nil {
                if let conversations = datas as? [JMSGConversation] {
                    self.dataArray=self.dataArray+conversations
                    
                    self.tableView.reloadData()
                }
            }
        }
        
    }

    /// 视图已经可见了
    ///
    /// - Parameter animated: <#animated description#>
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //监听消息
        
        //重新获取数据
        fetchData()
        
        //监听消息
        JMessage.add(self, with: nil)
    }
    
    /// 视图即将消失
    ///
    /// - Parameter animated: animated description
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        //界面不可见
        //移除监听
        //可以提高效率
        JMessage.remove(self, with: nil)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

// MARK: - 启动界面
extension MessageController {
    /// 启动界面
    ///
    /// - Parameter navigationController: <#navigationController description#>
    static func start(_ navigationController:UINavigationController) {
        //创建控制器
        let controller=navigationController.storyboard?.instantiateViewController(withIdentifier: "Message") as! MessageController
        
        //将控制器压入导航控制中
        navigationController.pushViewController(controller, animated: true)
        
    }
    
}

// MARK: - 列表数据源和代理
extension MessageController: UITableViewDataSource,UITableViewDelegate {
    
    // MARK:- TableView数据源
    /// 返回有多个条目
    /// 和CollectionView差不多
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回当前位置的Cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取Cell
        let cell=tableView.dequeueReusableCell(withIdentifier: CELL, for: indexPath) as! MessageCell
        
        return cell
    }
    
    /// 即将显示
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - cell: <#cell description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //取出数据
        guard let cell = cell as? MessageCell else {
            return
        }
        
        let data=dataArray[indexPath.row]

        cell.bindData(data)
    }
    
    /// Item点击事件
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data=dataArray[indexPath.row]
        
        let user=data.target as! JMSGUser
        
        //在注册的时候
        //给昵称传递的数据是用户Id
        //当然Id前面前一些填充数据
        //因为他要求Id长度不能小于4位
        ChatController.start(navigationController!,user.username)
        
    }
}

// MARK: - 聊天SDK消息回调
extension MessageController:JMessageDelegate {
//
//    /// 发送消息的回调
//    ///
//    /// - Parameters:
//    ///   - message: <#message description#>
//    ///   - error: <#error description#>
//    func onSendMessageResponse(_ message: JMSGMessage!, error: Error!) {
//        if let error = error {
//            print("MessageController onSendMessageResponse failed:\(error)")
//        }else{
//            print("MessageController onSendMessageResponse success")
//
//            fetchData()
//        }
//    }
    
    //极光聊天在线消息回调
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        fetchData()
    }
}
